package org.jflame.captcha.web;

import org.jflame.captcha.cache.CaptchaCache;
import org.jflame.captcha.validator.Verifiable;

import java.util.function.Supplier;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@SuppressWarnings("rawtypes")
public class CaptchaSessionCache implements CaptchaCache {

    private Supplier<HttpServletRequest> requestSupplier;

    public CaptchaSessionCache(Supplier<HttpServletRequest> requestSupplier) {
        this.requestSupplier = requestSupplier;
    }

    @Override
    public void put(String id, Verifiable v) {
        requestSupplier.get()
                .getSession(true)
                .setAttribute(id, v);
    }

    @Override
    public Verifiable get(String id) {
        HttpServletRequest request = requestSupplier.get();
        if (request != null) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                return (Verifiable) session.getAttribute(id);
            }
        }
        return null;
    }

    @Override
    public void evict(String id) {
        HttpServletRequest request = requestSupplier.get();
        if (request != null) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.removeAttribute(id);
            }
        }
    }

}
